import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { isHttp, isEmpty } from "@/utils/validate"
import defAva from '@/assets/images/profile.jpg'
import { listNotice } from "@/api/system/notice"
import { ElMessageBox } from 'element-plus'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      noticeCheckTimer: null,
      lastNoticeId: null,
      refreshTimer: null
    }),
    actions: {
      // 登录
      login(userInfo) {
        const { username, password, code, uuid } = userInfo
        return new Promise((resolve, reject) => {
          login(username, password, code, uuid).then(res => {
            setToken(res.token)
            this.token = res.token
            // 登录成功后启动通知检查
            this.startNoticeCheck()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res.user
            let avatar = user.avatar || ""
            if (!isHttp(avatar)) {
              avatar = (isEmpty(avatar)) ? defAva : import.meta.env.VITE_APP_BASE_API + avatar
            }
            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.id = user.userId
            this.name = user.userName
            this.avatar = avatar
            resolve(res)

            // 登录成功后启动通知检查
            this.startNoticeCheck()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            // 停止通知检查
            this.stopNoticeCheck()
            // 停止界面刷新
            this.stopPageRefresh()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 启动通知检查
      startNoticeCheck() {
        // 先清除可能存在的定时器
        this.stopNoticeCheck()

        // 立即执行一次检查
        this.checkNewNotices()

        // 设置定时器，每分钟检查一次
        this.noticeCheckTimer = setInterval(() => {
          this.checkNewNotices()
        }, 600000) // 60000毫秒 = 1分钟
      },
      // 停止通知检查
      stopNoticeCheck() {
        if (this.noticeCheckTimer) {
          clearInterval(this.noticeCheckTimer)
          this.noticeCheckTimer = null
        }
      },
      // 检查新通知
      checkNewNotices() {
        const params = {
          pageNum: 1,
          pageSize: 1,
          status: "0", // 只查询未读通知
          createBy: this.id
        }

        listNotice(params).then(response => {
          if (response.rows && response.rows.length > 0) {
            const latestNotice = response.rows[0]


            this.lastNoticeId = latestNotice.noticeId

            // 显示通知内容
            ElMessageBox.alert(latestNotice.noticeContent, "通知", {
              confirmButtonText: '确定',
              callback: () => {
              }
            })

          }
        }).catch(error => {
          console.error('检查通知失败:', error)
        })
      },
    }
  })

export default useUserStore
